package com.bw.a1908.ui.main;

import android.Manifest;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.TextView;

import com.blankj.utilcode.util.PermissionUtils;
import com.blankj.utilcode.util.SizeUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.bw.a1908.R;
import com.bw.a1908.core.mvp.BaseFragment;
import com.bw.a1908.core.mvp.IPresenter;
import com.tencent.live2.V2TXLiveDef;
import com.tencent.live2.V2TXLivePusher;
import com.tencent.live2.impl.V2TXLivePusherImpl;
import com.tencent.rtmp.TXLivePusher;
import com.tencent.rtmp.ui.TXCloudVideoView;

import top.littlefogcat.danmakulib.danmaku.Danmaku;
import top.littlefogcat.danmakulib.danmaku.DanmakuManager;

import static com.tencent.live2.V2TXLiveCode.V2TXLIVE_ERROR_INVALID_LICENSE;

/**
 * 默认Fragment 页面占位
 */
public class MineFragment extends BaseFragment<IPresenter> {


    private TXCloudVideoView mPusherView;
    private V2TXLivePusher mLivePusher;
    private Button button;
    private FrameLayout mFrameLayout;


    private DanmakuManager danmakuManager;

    @Override
    public int bandLayout() {
        return R.layout.fragment_live;
    }

    @Override
    public void initView() {
        PermissionUtils.permission(Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE).request();
        button = findViewById(R.id.fragment_start);
        mFrameLayout = findViewById(R.id.fragment_live);

        //启动本地摄像头预览
        mPusherView = findViewById(R.id.pusher_tx_cloud_view);

        mLivePusher = new V2TXLivePusherImpl(getContext(), V2TXLiveDef.V2TXLiveMode.TXLiveMode_RTMP); //指定对应的直播协议为 RTMP
        mLivePusher.setRenderView(mPusherView);
        mLivePusher.startCamera(true);


        //弹幕初始化
        danmakuManager = DanmakuManager.getInstance();
        danmakuManager.init(getContext(), mFrameLayout);
    }

    @Override
    public void initData() {
        findViewById(R.id.fragment_start).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                initDan();
//                start();
            }
        });
    }

    private void start() {
        //启动推流， URL 可以使用 trtc:// 或者 rtmp:// 两种协议，前者支持连麦功能
        String rtmpURL = "rtmp://3891.livepush.myqcloud.com/live/3891_user_9a9e432d_c50c?bizid=3891&txSecret=803852b93356d53e8bac9b521e46054e&txTime=61E11703";    //不支持连麦，直接推流到直播 CDN
        int ret = mLivePusher.startPush(rtmpURL.trim());
        if (ret == V2TXLIVE_ERROR_INVALID_LICENSE) {
            ToastUtils.showShort("验证失败");
        } else {
            ToastUtils.showShort("开始推流");
        }
    }

    private void stop() {
        mLivePusher.stopPush();
    }


    private void initDan() {
        //弹幕对象
        Danmaku danmaku = new Danmaku();
        danmaku.text = "text";
        danmaku.size = SizeUtils.sp2px(20);

        danmakuManager.send(danmaku);
    }
}
